package com.socket.nio.nio.chat.example.server;

import com.socket.nio.nio.chat.example.handler.ChatServerHandler;
import com.socket.nio.nio.chat.example.protocol.ChatMessage;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;

/**
 * @author Hexudong
 * @date 2025/5/12
 */
public class ChatServer {
  private final int port;

  public ChatServer(int port) {
    this.port = port;
  }

  public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
      ServerBootstrap b = new ServerBootstrap();
      b.group(bossGroup, workerGroup)
          .channel(NioServerSocketChannel.class)
          .childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) {
              ch.pipeline().addLast(
                  new ProtobufVarint32FrameDecoder(),
                  new ProtobufDecoder(ChatMessage.Msg.getDefaultInstance()),
                  new ProtobufVarint32LengthFieldPrepender(),
                  new ProtobufEncoder(),
                  new ChatServerHandler());
            }
          });

      ChannelFuture f = b.bind(port).sync();
      System.out.println("Server started on port " + port);
      f.channel().closeFuture().sync();
    } finally {
      workerGroup.shutdownGracefully();
      bossGroup.shutdownGracefully();
    }
  }

  public static void main(String[] args) throws Exception {
    new ChatServer(8082).run();
  }
}
